package com.example.llm;
import com.alibaba.fastjson.JSON;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import com.google.gson.Gson;

import com.example.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * ClassName:controlPlanController
 * Description:
 *
 * @Author 赵永峰
 * @Create 2024/5/23 15:17
 * @Version 1.0
 */
@RestController
@Slf4j
public class translateLargeModelController {

   //大模型翻译的统一地址
      @PostMapping("/translateLargeModel")
      public Result controlPlanTreeList(@RequestBody Map<String,Object> map){
          List<TranslationService.TranslationData> result =new ArrayList<>();
          //建立一个三语的Map，到时候反馈给前端。
          Map<String,String> translateData= new HashMap<>();
          //分解传来的Map数据；
          String text=(String) map.get("text");
          String from=(String) map.get("from");
        TranslationService service = new TranslationService();
        try {
            if (from.equals("zh")){
                //组合中文的内容
                translateData.put("zh",text);
                //翻译英文
                result = service.translate("zh", "en", text);
                String strEnglish="";
                for (int i = 0; i < result.get(0).sentences.size(); i++) {
                        strEnglish=strEnglish+result.get(0).sentences.get(i).data;
                }
                //组合英文
                translateData.put("en",strEnglish);
                //翻译俄文
                result = service.translate("zh", "ru", text);
                String strRussian="";
                for (int i = 0; i < result.get(0).sentences.size(); i++) {
                        strRussian=strRussian+result.get(0).sentences.get(i).data;
                }
                //组合俄文
                translateData.put("ru",strRussian);
            }
            else if (from.equals("en")){
                //组合中文的内容
                translateData.put("en",text);
                //翻译英文
                result = service.translate("en", "zh", text);
                String strChinese="";
                for (int i = 0; i < result.get(0).sentences.size(); i++) {
                    strChinese=strChinese+result.get(0).sentences.get(i).data;
                }
                //组合中文
                translateData.put("zh",strChinese);
                //翻译俄文
                result = service.translate("en", "ru", text);
                String strRussian="";
                for (int i = 0; i < result.get(0).sentences.size(); i++) {
                    strRussian=strRussian+result.get(0).sentences.get(i).data;
                }
                //组合俄文
                translateData.put("ru",strRussian);
            }
            else if (from.equals("ru")){
                //组合中文的内容
                translateData.put("ru",text);
                //翻译中文
                result = service.translate("ru", "zh", text);
                String strChinese="";
                for (int i = 0; i < result.get(0).sentences.size(); i++) {
                    strChinese=strChinese+result.get(0).sentences.get(i).data;
                }
                //组合中文
                translateData.put("zh",strChinese);
                //翻译英文
                result = service.translate("ru", "en", text);
                String strEnglish="";
                for (int i = 0; i < result.get(0).sentences.size(); i++) {
                    strEnglish=strEnglish+result.get(0).sentences.get(i).data;
                }
                //组合俄文
                translateData.put("en",strEnglish);
            }

        } catch (Exception e) {
            translateData.put("en","Translation unsuccessful");
            translateData.put("ru","Перевод не удался");
            e.printStackTrace();
        }

        return Result.success(translateData);
    }

    static class TranslationService {
        private static final String USER_SECRET_ID = "50";
        private static final String API_URL = "https://agent-prod-java.gwm.cn/interfaces/llm/translateText";
        private static   final String   publicKey="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCwkC+/XUSpR1bfnCxtiIUBs3m+Fe4oxfwJy5VO20Cws2/NnJ7GZcNwDpVck7tp5Aotn73NqT32dfTi+yWamiqods5v6zpv4XC9UpUZdEZyy+RaqKYBlfkrylwhZAnZiD5LdAsmOBC4yRSo7gAXzuet+zFe01elb5WR75/hYZN1hwIDAQAB";
        public List<TranslationData> translate(String sourceLang, String targetLang, String text) throws Exception {
            try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                HttpPost httpPost = new HttpPost(API_URL);
                long timestamp = System.currentTimeMillis() / 1000;
                String sign = RSAUtils.encryptedDataOnJava(timestamp + "", publicKey);
                // 设置请求头
                httpPost.setHeader("sign",sign );
                httpPost.setHeader("userSecretId", USER_SECRET_ID);
                httpPost.setHeader("Content-Type", "application/json");

                // 构建请求体
                Map<String, String> requestBody = new HashMap<>();
                requestBody.put("from", sourceLang);
                requestBody.put("to", targetLang);
                requestBody.put("text", text);

                Gson gson = new Gson();
                String jsonBody = gson.toJson(requestBody);
                httpPost.setEntity(new StringEntity(jsonBody, "UTF-8"));

                // 执行请求
                try (CloseableHttpResponse response = httpClient.execute(httpPost)) {
                    HttpEntity entity = response.getEntity();
                    if (entity != null) {
                        String responseString = EntityUtils.toString(entity);
                        // 解析响应
                        TranslationResponse translationResponse = gson.fromJson(responseString, TranslationResponse.class);
                        if (translationResponse.code == 200 &&
                                translationResponse.data != null
                               ) {
                            return translationResponse.data;
                        } else {
                            throw new RuntimeException("Translation failed: " + translationResponse.msg);
                        }
                    }
                }
            }
            throw new RuntimeException("Translation request failed");
        }

        // 响应对象结构
         class TranslationResponse {
            int code;
            String msg;
            java.util.List<TranslationData> data;
        }

         class TranslationData {
            int order;
            java.util.List<Sentence> sentences;

             public int getOrder() {
                 return order;
             }

             public void setOrder(int order) {
                 this.order = order;
             }

             public List<Sentence> getSentences() {
                 return sentences;
             }

             public void setSentences(List<Sentence> sentences) {
                 this.sentences = sentences;
             }
         }

      class Sentence {
            String data;
            Object polysemyVoList;  // 根据实际需要可定义具体类型
            String contrastSourceText;
            int paragraphOrder;
            int order;
            String uuid;
            Object historyResult;   // 根据实际需要可定义具体类型
            Integer len;
            String sourceLanguageAbbreviation;
            String targetLanguageAbbreviation;

          public String getData() {
              return data;
          }

          public void setData(String data) {
              this.data = data;
          }

          public Object getPolysemyVoList() {
              return polysemyVoList;
          }

          public void setPolysemyVoList(Object polysemyVoList) {
              this.polysemyVoList = polysemyVoList;
          }

          public String getContrastSourceText() {
              return contrastSourceText;
          }

          public void setContrastSourceText(String contrastSourceText) {
              this.contrastSourceText = contrastSourceText;
          }

          public int getParagraphOrder() {
              return paragraphOrder;
          }

          public void setParagraphOrder(int paragraphOrder) {
              this.paragraphOrder = paragraphOrder;
          }

          public int getOrder() {
              return order;
          }

          public void setOrder(int order) {
              this.order = order;
          }

          public String getUuid() {
              return uuid;
          }

          public void setUuid(String uuid) {
              this.uuid = uuid;
          }

          public Object getHistoryResult() {
              return historyResult;
          }

          public void setHistoryResult(Object historyResult) {
              this.historyResult = historyResult;
          }

          public Integer getLen() {
              return len;
          }

          public void setLen(Integer len) {
              this.len = len;
          }

          public String getSourceLanguageAbbreviation() {
              return sourceLanguageAbbreviation;
          }

          public void setSourceLanguageAbbreviation(String sourceLanguageAbbreviation) {
              this.sourceLanguageAbbreviation = sourceLanguageAbbreviation;
          }

          public String getTargetLanguageAbbreviation() {
              return targetLanguageAbbreviation;
          }

          public void setTargetLanguageAbbreviation(String targetLanguageAbbreviation) {
              this.targetLanguageAbbreviation = targetLanguageAbbreviation;
          }
      }

        // 使用示例

    }
   }